package ext;

import java.util.*;
import org.junit.*;

public class ParseNumToChinese {
    private static String[] unit = {"十", "百", "千", "万", "亿"};
    Map<Integer, String> map = new HashMap<>(){{
        put(1, "一");
        put(2, "二");
        put(3, "三");
        put(4, "四");
        put(5, "五");
        put(6, "六");
        put(7, "七");
        put(8, "八");
        put(9, "九");
        put(0, "零");
    }};
    public String parse(int n) {
        boolean flag = true;
        if (n == 0) {
            return "零";
        } else if (n < 0) {
            n = -n;
            flag = false;
        }
        int tmp = n % 10000;
        String th = parseThroud(tmp);
        n /= 10000;
        if (n == 0) {
            if (!flag) {
                th = "负" + th;
            }
            return th;
        } else if (tmp < 1000) {
            th = "零" + th;
        }

        int d = 3;
        while (n > 0) {
            tmp = n % 10000;
            String th2 = parseThroud(tmp) + unit[d++];
            n /= 10000;
            if (n == 0) {
                th2 = th2 + th;
                if (!flag) {
                    th2 = "负" + th2;
                }
                return th2;
            } else if (tmp < 1000) {
                th = "零" + th2 + th;
            } else {
                th = th2 + th;
            }
        }

        return th;
    }

    //转换一万以下的正数
    private String parseThroud(int n) {
        StringBuilder sb = new StringBuilder();
        int d = 0;
        int cur = n % 10;
        if (cur != 0) {
            sb.append(map.get(cur));
        }
        n /= 10;
        while (n != 0) {
            String u = unit[d++];
            cur = n % 10;
            if (cur == 0) {
                sb.insert(0, "零");
            } else {
                sb.insert(0, u);
                sb.insert(0, map.get(cur));
            }
            n /= 10;
        }
        int len;
        while ((len = sb.length()) > 0 && sb.charAt(len - 1) == '零') {
            sb.setLength(len - 1);
        }
        for (int i = 1; i < sb.length(); i++) {
            if (sb.charAt(i) == '零' && sb.charAt(i - 1) == '零') {
                sb.deleteCharAt(i);
                i--;
            }
        }
        return sb.toString();
    }

    @Test
    public void test() {
        System.out.println(parseThroud(101));
        System.out.println(parse(1119080651));
    }
}
